﻿using System;
using System.Collections.Generic;
using BearUtil.Hidden;
using Sirenix.OdinInspector;
using UnityEditor;
using UnityEngine;
using XNode;
using XNodeEditor;

namespace BearUtil
{
    [CreateNodeMenu(menuName:"自定义节点/对话节点"), Title("对话节点")]
    [Node.NodeTintAttribute("#1a6a9c"), Node.NodeWidthAttribute(250)]
    public class DialogNode : BearNode
    {
        [ReadOnly]
        public int id;
        /// <summary>
        /// 可能不是必须的一些属性
        /// </summary>
        [LabelText("基本属性")] public BasicProperty basic;
        
        [BoxGroup("对话表属性"), HideLabel] public DialogProperty property;

        /// <summary>
        /// 定义对话内容界面
        /// </summary>
        [SerializeField, HorizontalGroup("快速编辑"), LabelText("编辑界面"), OnValueChanged("BindGraph")]
        private DialogGraph selfGraph;

        public DialogGraph DialogGraph {
            get
            {
                return selfGraph;
            }
        }

        public DialogNode()
        {
            if (basic == null)
                basic = new BasicProperty();

            if (basic.audioData.SyncFontSpeedCallback == null)
                basic.audioData.SyncFontSpeedCallback = SyncFontSpeed;
        }

        public void SyncFontSpeed()
        {
            for (var i = 0; i < selfGraph.nodes.Count; i++)
            {
                var node = selfGraph.nodes[i] as TalkNode;
                if (node == null)
                    continue;

                node.FontSpeed = basic.audioData.FontSpeed;
            }
        }

        public void BindGraph(DialogGraph dialogGraph)
        {
            this.selfGraph = dialogGraph;
            selfGraph.owner = this;
        }

        [HorizontalGroup("快速编辑"), Button("编辑")]
        public void OpenGraph()
        {
            NodeEditorWindow.Open(selfGraph);
        }

        public void OnDestroy()
        {
            // selfGraph.DeleteSelf();
        }

        /// <summary>
        /// 数据更新需求，要求旧数据不要丢失
        /// </summary>
        public override void Transform()
        {
            base.Transform();

            if (property.triggerEvents != null)
            {
                if (property.triggerEvents == null)
                    property.triggerEvents = new List<StoryTriggerEvent>();
                property.triggerEvents.Clear();
            
                property.triggerEvents.Add(property.trigger_event);
            }


            if (!string.IsNullOrEmpty(property.trigger_param))
            {
                if (property.triggerParams == null)
                    property.triggerParams = new List<int>();
                property.triggerParams.Clear();
            
                property.triggerParams.Add(Convert.ToInt32(property.trigger_param));
            }
            
            EditorUtility.SetDirty(this);
            AssetDatabase.Refresh();
        }
    }
}